class VoteObserver < ActiveRecord::Observer
  
  def after_create(vote)
    update_user_points_and_votes_count(vote,1)
    update_owner_points(vote)
  end
  
  def after_destroy(vote)
    update_user_points_and_votes_count(vote,-1)
    
  end
  
  private 
  def update_owner_points(vote)
    #find the ownler of content
    # content
    content_clazz = Kernel.const_get(vote.voteable_type)
    #get the user
    content = content_clazz.find(vote.voteable_id)
    
    
    if content.user_id!=vote.user_id
      user = User.find(content.user_id)    
      points = (user.active_campaign.points_content_voted if user.active_campaign) || WebappConstants::ACTIVITY_POINTS[:content_voted]
      user.points = 0 unless  user.points
      user.points +=points
      user.save!
      
      
      
      user_campaign = user.active_user_campaign
      if user_campaign
        user_campaign.points +=points
        user_campaign.points = 0 if user_campaign.points < 0
        user_campaign.save!  
      end
      
    end
    
  end
  
  def update_user_points_and_votes_count(vote, factor)
    #get the number of points for this resource
    user = User.find(vote.user_id)
    points = (user.active_campaign.points_vote_content if user.active_campaign) || WebappConstants::ACTIVITY_POINTS[:voting]
    content_clazz = Kernel.const_get(vote.voteable_type)
    #get the user
    content = content_clazz.find(vote.voteable_id)
    if content.user_id!=user.id
      
      user.points = 0 unless  user.points
      user.points +=(factor*points)
      user.save!
      
      content.vote_count +=1*factor
      content.save!
      
      user_campaign = user.active_user_campaign
      if user_campaign
        user_campaign.points +=(factor*points)
        user_campaign.points = 0 if user_campaign.points < 0
        user_campaign.save  
      end    
    end
    
    
  end
end
